# -*- coding: utf-8 -*-
import threading
import  time
import datetime
import heapq

# Create your views here.

class deviceTaskThread(threading.Thread):  
    def __init__(self, name=''):  
        threading.Thread.__init__(self)  
        self.name = name
        self.__flag = threading.Event()     # 用于暂停线程的标识
        self.taskList = []

    def getResult(self):  
        return self.res  
      
    def run(self): #run()函数
        while(self.__flag.wait()):
            if(self.hasTask()): # 检查是否有任务
                local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
                if(self.taskList[0][0] <= local_time): #如果任务中的时间在当前时间之后
                    task = self.popTask()
                    if(task!=None):
                        print "Starting", self.name, 'at:', task[0]
                        self.res = apply(task[1], task[2])

    def pushTak(self, _time, _task, _args):
        #time时间格式(2016-05-09 18:59:20)
        self.__flag.set()
        try:
            TimeTask = [_time, _task, _args]
            heapq.heappush(self.taskList, TimeTask)
            self.__flag.set()

            # time.strptime(_time, "%Y-%m-%d %H:%M:%S")
            # self.taskList.insert(0,TimeTask)
            # for index, item in enumerate(self.taskList):
            #     if(dt < item[0]):
            #         self.taskList.insert(index,TimeTask)
            #         break
            #     elif(dt >= item[0]):
            #         continue
        except BaseException as e:
            e.message
       

    def popTask(self):
        if(len(self.taskList) > 0):
            return heapq.heappop(self.taskList)
        else:
            self.__flag.clear()
            return None

    def hasTask(self):
        if(len(self.taskList) > 0):
            self.__flag.set()
            return True
        else:
            self.__flag.clear()
            return False

    def __str__(self):
        return str(self.taskList)


if __name__ == "__main__":
    deviceTaskThread = deviceTaskThread()
    def doAction(_string):
        print _string

    a = '2018-05-21 16:01:00'
    deviceTaskThread.pushTak(a, doAction, ('hello',))
    deviceTaskThread.start()
    count = 10
    while(count):
        count = count - 1
        time_int = time.time()
        local_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
        deviceTaskThread.pushTak(local_time, doAction, ('hello',))